//
//  GoodsChooseView.m
//  AddShoppingCartDemo
//
//  Created by Jim1024 on 2016/12/23.
//  Copyright © 2016年 Jim1024. All rights reserved.
//

#import "GoodsChooseView.h"
#import "BuyCountView.h"
#import "GoodsTypeView.h"

@interface GoodsChooseView () <UITextFieldDelegate, GoodsTypeViewDelegete>

@property (nonatomic, strong) UIView *goodsContainView; // 装载商品信息的视图
@property (nonatomic, strong) UIImageView *iconView; // 商品图片

@property (nonatomic, strong) UILabel *priceLb;
@property (nonatomic, strong) UILabel *stockLb;
@property (nonatomic, strong) UILabel *detailLb;
@property (nonatomic, strong) UILabel *lineLb;

@property (nonatomic, strong) UIScrollView *mainscrollview;
@property (nonatomic, strong) GoodsTypeView *sizeView;
@property (nonatomic, strong) GoodsTypeView *colorView;
@property (nonatomic, strong) BuyCountView *countView;

@property (nonatomic, strong) NSArray *sizeArr;
@property (nonatomic, strong) NSArray *colorArr;
@property (nonatomic, strong) NSDictionary *stockDict;
@property (nonatomic, assign ) NSInteger stockNum;

@end

@implementation GoodsChooseView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        // 半透明视图
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _maskView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.2];
        [self addSubview:_maskView];
        // 装载商品信息的视图
        _goodsContainView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.frame.size.width, self.frame.size.height - 200)];
        _goodsContainView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_goodsContainView];
        UITapGestureRecognizer *goodsTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGoodsTap)];
        [_goodsContainView addGestureRecognizer:goodsTap];
        
        // 商品图片
        _iconView = [[UIImageView alloc] initWithFrame:CGRectMake(10, -20, 100, 100)];
        _iconView.contentMode = UIViewContentModeScaleAspectFill;
        _iconView.image = [UIImage imageNamed:@"1.jpg"];
        _iconView.backgroundColor = [UIColor yellowColor];
        _iconView.layer.cornerRadius = 4;
        _iconView.layer.borderColor = [UIColor whiteColor].CGColor;
        _iconView.layer.borderWidth = 5;
        _iconView.layer.masksToBounds = YES;
        [_goodsContainView addSubview:_iconView];
        
        _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancleBtn.frame = CGRectMake(_goodsContainView.frame.size.width-40, 10,30, 30);
        [_cancleBtn setBackgroundImage:[UIImage imageNamed:@"close@3x"] forState:UIControlStateNormal];
        [_goodsContainView addSubview:_cancleBtn];
        
        //商品价格
        _priceLb = [[UILabel alloc] initWithFrame:CGRectMake(_iconView.frame.origin.x+_iconView.frame.size.width+20, 10, _goodsContainView.frame.size.width-(_iconView.frame.origin.x+_iconView.frame.size.width+40+40), 20)];
        _priceLb.textColor = [UIColor redColor];
        _priceLb.font = [UIFont systemFontOfSize:14];
        [_goodsContainView addSubview:_priceLb];
        
        //商品库存
        _stockLb = [[UILabel alloc] initWithFrame:CGRectMake(_iconView.frame.origin.x+_iconView.frame.size.width+20, _priceLb.frame.origin.y+_priceLb.frame.size.height, _goodsContainView.frame.size.width-(_iconView.frame.origin.x+_iconView.frame.size.width+40+40), 20)];
        _stockLb.textColor = [UIColor blackColor];
        _stockLb.font = [UIFont systemFontOfSize:14];
        [_goodsContainView addSubview:_stockLb];
        
        // 用户所选择商品的尺码和颜色
        _detailLb = [[UILabel alloc] initWithFrame:CGRectMake(_iconView.frame.origin.x+_iconView.frame.size.width+20, _stockLb.frame.origin.y+_stockLb.frame.size.height, _goodsContainView.frame.size.width-(_iconView.frame.origin.x+_iconView.frame.size.width+40+40), 40)];
        _detailLb.numberOfLines = 2;
        _detailLb.textColor = [UIColor blackColor];
        _detailLb.font = [UIFont systemFontOfSize:14];
        [_goodsContainView addSubview:_detailLb];
        
        // 分界线
        _lineLb = [[UILabel alloc] initWithFrame:CGRectMake(0, _iconView.frame.origin.y+_iconView.frame.size.height+20, _goodsContainView.frame.size.width, 0.5)];
        _lineLb.backgroundColor = [UIColor lightGrayColor];
        [_goodsContainView addSubview:_lineLb];
        
        //确定按钮
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureBtn.frame = CGRectMake(0, _goodsContainView.frame.size.height-50,_goodsContainView.frame.size.width, 50);
        [_sureBtn setBackgroundColor:[UIColor redColor]];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:0];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        [_sureBtn setTitle:@"确定" forState:0];
        [_goodsContainView addSubview:_sureBtn];
        
        // 有的商品尺码和颜色分类特别多 所以用UIScrollView 分类过多显示不全的时候可滑动查看
        _mainscrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_lineLb.frame), _goodsContainView.frame.size.width, _sureBtn.frame.origin.y-CGRectGetMaxY(_lineLb.frame))];
        _mainscrollview.showsHorizontalScrollIndicator = NO;
        _mainscrollview.showsVerticalScrollIndicator = NO;
        [_goodsContainView addSubview:_mainscrollview];
        
        // 购买数量的视图
        _countView = [[BuyCountView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50)];
        [_mainscrollview addSubview:_countView];
        [_countView.addBtn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
        _countView.countTf.delegate = self;
        [_countView.reduceBtn addTarget:self action:@selector(reduce) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)initTypeViewWithSizeArr:(NSArray *)sizeArr colorArr:(NSArray *)colorArr stockDic:(NSDictionary *)stockDic {
    _sizeArr = sizeArr;
    _colorArr = colorArr;
    _stockDict = stockDic;
    
    // 尺码
    _sizeView = [[GoodsTypeView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50) datasource:sizeArr typeName:@"尺码"];
    _sizeView.delegate = self;
    [_mainscrollview addSubview:_sizeView];
    _sizeView.frame = CGRectMake(0, 0, self.frame.size.width, _sizeView.viewHeight);
    
    // 颜色分类
    _colorView = [[GoodsTypeView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50) datasource:colorArr typeName:@"颜色分类"];
    _colorView.delegate = self;
    [_mainscrollview addSubview:_colorView];
    _colorView.frame = CGRectMake(0, _sizeView.frame.size.height, self.frame.size.width, _colorView.viewHeight);
    
    // 购买数量
    _countView.frame = CGRectMake(0, CGRectGetMaxY(_colorView.frame), self.frame.size.width, 50);
    _mainscrollview.contentSize = CGSizeMake(self.frame.size.width, CGRectGetMaxY(_countView.frame));
    
    _priceLb.text = @"¥100";
    _stockLb.text = @"库存100000件";
    _detailLb.text = @"请选择 尺码 颜色分类";
    
    // 点击图片放大图片
    UITapGestureRecognizer *imgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBigImage:)];
    _iconView.userInteractionEnabled = YES;
    [_iconView addGestureRecognizer:imgTap];
    
}

#pragma mark - GoodsTypeViewDelegete

- (void)selectButtonIndex:(NSInteger)index {
    // 通过seletIndex >= 0来判断尺码和颜色是否被选择，－1则是未选择状态
    if (_sizeView.seletIndex >= 0 && _colorView.seletIndex >= 0) {
        // 尺码和颜色都选择的时候
        NSString *size = [_sizeArr objectAtIndex:_sizeView.seletIndex];
        NSString *color = [_colorArr objectAtIndex:_colorView.seletIndex];
        _stockLb.text = [NSString stringWithFormat:@"库存%@件",[[_stockDict objectForKey: size] objectForKey:color]];
        _detailLb.text = [NSString stringWithFormat:@"已选 \"%@\" \"%@\"",size,color];
        _stockNum = [[[_stockDict valueForKey:size] valueForKey:color] integerValue];
        
        [self reloadTypeButtonWithDict:[_stockDict valueForKey:size] array:_colorArr typeView:_colorView];
        [self reloadTypeButtonWithDict:[_stockDict valueForKey:color] array:_sizeArr typeView:_sizeView];
        NSLog(@"%zd",_colorView.seletIndex);
        _iconView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%zd.jpg",_colorView.seletIndex+1]];
    } else if (_sizeView.seletIndex == -1 && _colorView.seletIndex == -1) { // 尺码和颜色都没选的时候
        //尺码和颜色都没选的时候
        _priceLb.text = @"¥100";
        _stockLb.text = @"库存100000件";
        _detailLb.text = @"请选择 尺码 颜色分类";
        _stockNum = 100000;
        // 全部恢复可点击状态
        [self resumeTypeView:_colorView withArray:_colorArr];
        [self resumeTypeView:_sizeView withArray:_sizeArr];
    } else if (_sizeView.seletIndex == -1 && _colorView.seletIndex >= 0) {
        //只选了颜色
        NSString *color =[_colorArr objectAtIndex:_colorView.seletIndex];
        // 根据所选颜色 取出该颜色对应所有尺码的库存字典
        NSDictionary *dict = [_stockDict objectForKey:color];
        [self reloadTypeButtonWithDict:dict array:_sizeArr typeView:_sizeView];
        [self resumeTypeView:_colorView withArray:_colorArr];
        _stockLb.text = @"库存100000件";
        _detailLb.text = @"请选择 尺码";
        _stockNum = 100000;
        
        _iconView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%zd.jpg",_colorView.seletIndex+1]];
    } else if (_sizeView.seletIndex >= 0 && _colorView.seletIndex == -1) {
        // 只选了尺码
        NSString *size =[_sizeArr objectAtIndex:_sizeView.seletIndex];
        // 根据所选尺码 取出该尺码对应所有颜色的库存字典
        NSDictionary *dict = [_stockDict objectForKey:size];
        [self reloadTypeButtonWithDict:dict array:_colorArr typeView:_colorView];
        [self resumeTypeView:_sizeView withArray:_sizeArr];
        _stockLb.text = @"库存100000件";
        _detailLb.text = @"请选择 尺码";
        _stockNum = 100000;
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _mainscrollview.contentOffset = CGPointMake(0, _countView.frame.origin.y);
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    int count =[textField.text intValue];
    if (count > self.stockNum) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数量超出范围" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.tag = 100;
        [alert show];
        textField.text = [NSString stringWithFormat:@"%zd", self.stockNum];
        [self handleGoodsTap];
    }
}

#pragma mark - UIAction

- (void)handleGoodsTap {
    _mainscrollview.contentOffset = CGPointMake(0, 0);
    [_countView.countTf resignFirstResponder];
}

- (void)add {
    NSInteger count =[_countView.countTf.text intValue];
    if (count < self.stockNum) {
        _countView.countTf.text = [NSString stringWithFormat:@"%zd", count + 1];
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数量超出范围" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)reduce {
    int count =[_countView.countTf.text intValue];
    if (count > 1) {
        _countView.countTf.text = [NSString stringWithFormat:@"%zd", count - 1];
    }
}

-(void)showBigImage:(UITapGestureRecognizer *)tap {
    NSLog(@"放大图片");
}

#pragma mark - Private Method

- (void)reloadTypeButtonWithDict:(NSDictionary *)dict array:(NSArray *)arr typeView:(GoodsTypeView *)typeView {
    for (int i = 0; i < arr.count; i++) {
        NSInteger count = [[dict valueForKey:[arr objectAtIndex:i]] integerValue];
        UIButton *btn = [typeView viewWithTag:100 + i];
        btn.selected = NO;
        [btn setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
        // 库存为零 不可点击
        if (count == 0) {
            btn.enabled = NO;
            [btn setTitleColor:[UIColor lightGrayColor] forState:0];
        } else {
            btn.enabled = YES;
            [btn setTitleColor:[UIColor blackColor] forState:0];
        }
        // 根据seletIndex 确定用户当前点了那个按钮
        if (i == typeView.seletIndex) {
            btn.selected = YES;
            [btn setBackgroundColor:[UIColor redColor]];
        }
    }
}

/// 恢复按钮的原始状态
- (void)resumeTypeView:(GoodsTypeView *)typeView withArray:(NSArray *)arr {
    for (int i = 0; i < arr.count; i++) {
        UIButton *btn =(UIButton *)[typeView viewWithTag:100+i];
        btn.enabled = YES;
        btn.selected = NO;
        [btn setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
        [btn setTitleColor:[UIColor blackColor] forState:0];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        if (i == typeView.seletIndex) {
            btn.selected = YES;
            [btn setBackgroundColor:[UIColor redColor]];
        }
    }
}

@end
